package com.palm.easy;

import com.palm.easy.domain.Service;
import com.palm.easy.service.Server;
import com.palm.easy.service.ServerManageService;
import org.noear.nami.coder.hessian.HessianDecoder;
import org.noear.nami.coder.hessian.HessianEncoder;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ServerEndpoint;
import org.noear.solon.core.Aop;
import org.noear.solon.core.message.Listener;
import org.noear.solon.core.message.Message;
import org.noear.solon.core.message.MessageFlag;
import org.noear.solon.core.message.Session;
import org.noear.solon.socketd.SocketD;

import java.io.File;
import java.io.IOException;
@ServerEndpoint(value="**")
public class ServerListener implements Listener {

    ServerManageService manageService;

    String token;
    public ServerListener(){
        Aop.getAsyn(ServerManageService.class,bw->manageService=bw.get());
        token= Solon.cfg().get("manager.token","");
    }
    @Override
    public void onOpen(Session session) {
        String path=session.path();
        if("/server".equals(path)){
            //服务器注册
            String reqToken= session.param("token");
            if(!token.equals(reqToken)){
                try {
                    session.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            Server server= SocketD.create(session, HessianEncoder.instance, HessianDecoder.instance, Server.class);
            String  addr=server.host();
            session.setAttachment(addr);
            manageService.regServer(addr,server);
        }else if("/client".equals(path)){
            //客户端注册
        }else{
            try {
                session.close();
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onMessage(Session session, Message message) throws IOException {
        if(message.flag()== MessageFlag.heartbeat){
            //心跳包 跳过
        }else if(message.flag()==MessageFlag.response){
            //响应消息，跳过

        }else{
           // System.out.println(message);
        }

    }

    @Override
    public void onClose(Session session) {
       String addr= session.getAttachment();
        if(addr!=null){
            manageService.remove(addr);
        }

    }
}
